#include <stdio.h>
#include <string.h>

#include "config.h"
#include "STC32G_Timer.h"
#include "STC32G_GPIO.h"
#include "STC32G_NVIC.h"
#include "STC32G_Exti.h"

#include "app_config.h"
#include "drv_iouart.h"
#include "debug.h"

#if TCFG_DRV_IOUART_SUPPORT

#define TIMER1_TICK_HEAD         19200  // 52us    104/2=52us  半个开始信号的时间
#define TIMER1_TICK_DATA         9600UL // 104us   1000000/9600=104.16us 一个数据位的时间

enum {
    E_IO_UART_STATE_IDLE=0,     // 空闲状态
    E_IO_UART_STATE_START,      // 开始接收数据
    E_IO_UART_STATE_END,        // 数据接收完成
};


struct io_uart_t {
    uint8_t state : 4;
    uint8_t ready : 4;
    uint8_t index;
    uint8_t _data;
    uint8_t rxlen;
    uint8_t _recv[7];
};


static struct io_uart_t io_uart;


void io_uart_driver_init(void)
{
    TIM_InitTypeDef		TIM_InitStructure;
    EXTI_InitTypeDef	Exti_InitStructure;

#if 1   // FOR DEBUG
    GPIO_InitTypeDef GPIO_IniStructure;
    GPIO_IniStructure.Pin = GPIO_Pin_1;
    GPIO_IniStructure.Mode = GPIO_OUT_PP;
    GPIO_Inilize(GPIO_P3, &GPIO_IniStructure);
#endif

    // TODO: IR信号输入 外部中断  边沿触发
    P3_MODE_IO_PU(GPIO_Pin_3);		//P3.0~P3.7 设置为准双向口
	P3_PULL_UP_ENABLE(GPIO_Pin_3);    //P3 口内部上拉电阻使能
    Exti_InitStructure.EXTI_Mode      = EXT_MODE_Fall;//中断模式,   EXT_MODE_RiseFall,EXT_MODE_Fall
    Ext_Inilize(EXT_INT1, &Exti_InitStructure);				//初始化
	NVIC_INT1_Init(ENABLE,Priority_1);		//中断使能, ENABLE/DISABLE; 优先级(低到高) Priority_0,Priority_1,Priority_2,Priority_3
    
    // TODO: IR解码定时器100us
    TIM_InitStructure.TIM_Mode      = TIM_16BitAutoReload;	//指定工作模式,   TIM_16BitAutoReload,TIM_16Bit,TIM_8BitAutoReload,TIM_16BitAutoReloadNoMask
	TIM_InitStructure.TIM_ClkSource = TIM_CLOCK_1T;		//指定时钟源, TIM_CLOCK_1T,TIM_CLOCK_12T,TIM_CLOCK_Ext
	TIM_InitStructure.TIM_ClkOut    = DISABLE;				//是否输出高速脉冲, ENABLE或DISABLE
	TIM_InitStructure.TIM_Value     = (u16)(65536UL - (MAIN_Fosc / TIMER1_TICK_HEAD));			//初值,
	TIM_InitStructure.TIM_PS        = 0;					//8位预分频器(n+1), 0~255
	TIM_InitStructure.TIM_Run       = DISABLE;				//是否初始化后启动定时器, ENABLE或DISABLE
	Timer_Inilize(Timer2,&TIM_InitStructure);				//初始化Timer1	  Timer0,Timer1,Timer2,Timer3,Timer4
	NVIC_Timer2_Init(ENABLE,Priority_1);		//中断使能, ENABLE/DISABLE; 优先级(低到高) Priority_0,Priority_1,Priority_2,Priority_3

    // TODO: 初始化状态
    
}

void INT1_ISR_Handler (void) interrupt INT1_VECTOR		//进中断时已经清除标志
{
    P31 = !P31;
    T2_Load((u16)(65536UL - (MAIN_Fosc / TIMER1_TICK_HEAD)));
    Timer2_Run(1);	// 启动定时器

    io_uart.state = (uint8_t)E_IO_UART_STATE_IDLE;    
    NVIC_INT1_Init(DISABLE,NULL);
		
}

void Timer2_ISR_Handler (void) interrupt TMR2_VECTOR		//进中断时已经清除标志
{
	// TODO: 在此处添加用户代码
    uint8_t checksum = 0;
    P31 = !P31;  // for test

    if (io_uart.state == E_IO_UART_STATE_START) {
        // P31 = !P31; // FOR TEST
        io_uart._data = io_uart._data >> 1; // 数据右移一位
        if (P33 == 1) { 
            io_uart._data |= 0x80;    // 如读取到的串口GPIO电平为高，高位位或运算
        }

        io_uart.index++;
        if (io_uart.index == 8) {
            io_uart.state = E_IO_UART_STATE_END;
            INT1_Mode(EXT_MODE_Fall);
            //NVIC_INT1_Init(ENABLE,Priority_0);        
            Timer2_Stop();
            // IO_INT_Enable(  GPIO_P0,GPIO_Pin_6);
            // IRQ_Enable(IT_GPIO0);
            // TR1=0;

            if (io_uart._data == 0xAA) {
                io_uart.rxlen = 0;
                memset(io_uart._recv, 0, sizeof(io_uart._recv));
            }
            io_uart._recv[io_uart.rxlen] = io_uart._data;
            io_uart.rxlen++;
            if (io_uart.rxlen == 7)
            {
                checksum = (uint8_t)(io_uart._recv[1]+io_uart._recv[2]+io_uart._recv[3]+io_uart._recv[4]);
                if (checksum == io_uart._recv[5]) {
                    // TODO: 和校验正确
                    //P31 = ~P31; // FOR TEST
                    // _this->sensor_co.covol = (uint16_t)(io_uart._recv[1]<<8 | io_uart._recv[2]);
                    io_uart.ready = 1;
                }
            }
        }
    }

    if (io_uart.state == E_IO_UART_STATE_IDLE) {
        io_uart.state = E_IO_UART_STATE_START;
        io_uart.index = 0;
        io_uart._data = 0;

        T2_Load((u16)(65536UL - (MAIN_Fosc / TIMER1_TICK_DATA)));
        Timer2_Run(1);	// 启动定时器
    }
}

#endif
